package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * DishServiceImpl
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/7/28 14:10
 */
@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DishDTO dishDTO) {
        Set keys = redisTemplate.keys("dishs::*");
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
        // 1. 向 菜品表写入数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.ENABLE);
        // 主键返回
        dishMapper.insert(dish);

        // 2. 向 菜品口味关联表 写入数据
        insertDishFlavors(dishDTO, dish.getId());

    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dish);
        Page<Dish> dishPage = dishMapper.selectPage(dish);
        return new PageResult(dishPage.getTotal(), dishPage.getResult());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> ids) {
        Set keys = redisTemplate.keys("dishs::*");
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
        Integer count = dishMapper.selectCountByIdsWithStatus(ids, StatusConstant.ENABLE);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        Integer countBySetmealDish = setmealDishMapper.selectCountByDishIds(ids);
        if (countBySetmealDish > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 1. 删除菜品
        dishMapper.deleteByIds(ids);
        // 2. 删除口味信息
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO queryById(Long id) {
        // 1. 菜品表查询
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        // 2. 口味表查询
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        if (dishFlavors != null && dishFlavors.size() > 0) {
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DishDTO dishDTO) {
        Set keys = redisTemplate.keys("dishs::*");
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
        // 1. 更新菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        // 2. 清空口味
        ArrayList<Long> disIds = new ArrayList<>();
        disIds.add(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(disIds);
        // 3. 新增口味
        insertDishFlavors(dishDTO, dish.getId());
    }

    @Override
    public List<DishVO> listByCategoryId(Long categoryId) {
        long startRedis = System.currentTimeMillis();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String cacheKey = "dishs::" + categoryId;
        String json = (String) valueOperations.get(cacheKey);
        if (StringUtils.isNotBlank(json)) {
            // 存在 数据不一致问题
            List<DishVO> dishVOList = JSON.parseArray(json, DishVO.class);
            long endRedis = System.currentTimeMillis();
            log.info("--------------通过Redis查询时间:{}ms--------------", endRedis - startRedis);
            return dishVOList;
        }
        long startSql = System.currentTimeMillis();
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        List<Long> dishIds = dishList.stream()
                .map(Dish::getId)
                .collect(Collectors.toList());
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectListByDishIds(dishIds);
        List<DishVO> dishVOS = dishList.stream()
                .map(dish -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(dish, dishVO);
                    List<DishFlavor> flavors = dishFlavors.stream()
                            .filter(item -> Objects.equals(item.getDishId(), dish.getId()))
                            .collect(Collectors.toList());
                    dishVO.setFlavors(flavors);
                    return dishVO;
                }).collect(Collectors.toList());
        long endSql = System.currentTimeMillis();
        log.info("--------------查询数据库查询时间:{}ms--------------", endSql - startSql);
        // dishVOS缓存起来
        String jsonString = JSON.toJSONString(dishVOS);
        valueOperations.set(cacheKey, jsonString, 1L, TimeUnit.DAYS);
        return dishVOS;
    }

    /**
     * 批量插入菜品口味 CTRL + ALT + M
     *
     * @param dishDTO 菜dto
     * @param dishId  dishId
     */
    private void insertDishFlavors(DishDTO dishDTO, Long dishId) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }
}
